<script setup lang="ts">
import { computed, reactive, toRefs, ref, onMounted, h } from "vue";
import type { FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Delete } from "@element-plus/icons-vue";
import dictionaryApi from "@/api/dictionary";
import colorName from "color-name";
import type {
  ButtonsCallBackParams,
  PlusPageInstance,
  PlusColumn,
  PageInfo
} from "plus-pro-components";
import { useTable } from "plus-pro-components";
defineOptions({
  name: "DictionaryItem"
});
import { useRoute } from "vue-router";
const route = useRoute();
const commonColors = [
  "red", // 红
  "orange", // 橙
  "yellow", // 黄
  "green", // 绿
  "cyan", // 青
  "blue", // 蓝
  "purple" // 紫
];

const colorNamesChinese = {
  red: "红",
  orange: "橙",
  yellow: "黄",
  green: "绿",
  cyan: "青",
  blue: "蓝",
  purple: "紫"
};

const commonColorsWithRGB = commonColors.map(color => ({
  label: colorNamesChinese[color],
  value: color,
  rgb: colorName[color] // Assuming colorName is a predefined object with color names as keys and RGB values as values.
}));

interface TableRow {
  id: number;
  createTime: string | null;
  label: string;
  value: number;
  color: string;
  sort: number;
}

interface State {
  /**
   * 检索数据
   */
  query?: any;
  /**
   * 当前选择的行数据
   */
  currentRow: Partial<TableRow>;
  /**
   * 表单弹窗是否可见
   */
  visible: boolean;
  /**
   * 详情弹窗是否可见
   */
  detailsVisible: boolean;
  /**
   * 当前选择多行的id集合
   */
  selectedIds: number[];
  /**
   *  提交loading
   */
  confirmLoading: boolean;
  /**
   * 是否是创建
   */
  isCreate: boolean;
  /**
   * 是否批量
   */
  isBatch: boolean;
  /**
   * 表单
   */
  form: {
    color: string;
  };
  /**
   * 校验
   */
  rules: FormRules;
}

const plusPageInstance = ref<PlusPageInstance | null>(null);
const state = reactive<State>({
  query: { groupName: "" },
  currentRow: {},
  visible: false,
  detailsVisible: false,
  confirmLoading: false,
  isCreate: true,
  isBatch: false,
  selectedIds: [],
  form: {
    color: ""
  },
  rules: {
    label: {
      required: true,
      message: "请输入",
      trigger: "blur"
    },
    value: {
      required: true,
      message: "请输入",
      trigger: "blur"
    },
    color: {
      required: true,
      message: "请选择",
      trigger: "blur"
    }
  }
});

const dialogTitle = computed(() => (state.isCreate ? "新增" : "编辑"));
const { buttons } = useTable();
const columns: PlusColumn[] = [
  {
    label: "排序",
    prop: "sort",
    hideInSearch: true,
    valueType: "input-number"
  },
  {
    label: "字典编号",
    prop: "id",
    minWidth: 30,
    hideInSearch: true,
    hideInForm: true,
    hideInTable: true
  },
  {
    label: "字典标签",
    prop: "label",
    hideInSearch: true
  },
  {
    label: "字典键值",
    prop: "value",
    hideInSearch: true,
    valueType: "input-number"
  },
  {
    label: "色值",
    prop: "color",
    hideInSearch: true,
    valueType: "select",
    options: commonColorsWithRGB,
    fieldProps: {
      filterable: true
    }
  },
  {
    label: "创建时间",
    prop: "createTime",
    valueType: "date-picker",
    hideInSearch: true,
    hideInForm: true
  }
];
// 按钮
buttons.value = [
  {
    text: "编辑",
    code: "update",
    props: { type: "success" }
  },
  {
    text: "删除",
    code: "delete",
    confirm: true,
    props: { type: "warning" }
  }
];

// 按钮操作
const handleTableOption = ({ row, buttonRow }: ButtonsCallBackParams): void => {
  state.currentRow = { ...row };
  switch (buttonRow.code) {
    case "update":
      state.form = { ...row } as any;
      state.isCreate = false;
      state.visible = true;
      break;
    case "delete":
      state.isBatch = false;
      handleDelete();
      break;
    case "view":
      state.detailsVisible = true;
      break;
    case "item":
      break;
  }
};

// 重新请求列表接口
const refresh = () => {
  plusPageInstance.value?.getList();
};

// 删除
const handleDelete = async (): Promise<void> => {
  try {
    const params = state.isBatch
      ? state.selectedIds
      : [state.currentRow.id as number];
    // await GroupServe.delete(params);
    await dictionaryApi.dictionaryDataDelete({ ids: params });
    ElMessage.success("删除成功");
    refresh();
  } catch (error) {}
};

// 批量删除
const handleBatchDelete = async () => {
  if (!state.selectedIds.length) {
    ElMessage.warning("请选择数据！");
    return;
  }
  try {
    await ElMessageBox.confirm("确定删除所选数据", "提示");
    state.isBatch = true;
    handleDelete();
  } catch (error) {
    console.log(error);
  }
};

// 选择
const handleSelect = (data: any) => {
  state.selectedIds = [...data].map(item => item.id);
};

// 创建
const handleCreate = (): void => {
  state.currentRow = {};
  state.form = {
    color: ""
  };
  state.isCreate = true;
  state.visible = true;
};

// 取消
const handleCancel = () => {
  state.visible = false;
};

// 提交表单成功
const handleSubmit = async () => {
  try {
    state.confirmLoading = true;
    const params = { ...state.form };
    if (state.isCreate) {
      // await GroupServe.create(params);
      await dictionaryApi.dictionaryDataCreate(
        Object.assign(
          {},
          params,
          { id: route.query.id },
          { rgb: colorName[state.form.color] }
        )
      );
      ElMessage.success("创建成功");
    } else {
      // await GroupServe.update(params);
      await dictionaryApi.dictionaryDataUpdate(params);
      ElMessage.success("更新成功");
    }
    handleCancel();
    refresh();
  } catch (error) {}
  state.confirmLoading = false;
};

const getList = async (query: PageInfo) => {
  const result = await dictionaryApi.dictionaryDataAll(
    Object.assign(
      {},
      {
        code: route.query.code,
        id: route.query.id
      }
    )
  );
  return { data: result.data };
};

const { form, confirmLoading, rules, currentRow, visible, detailsVisible } =
  toRefs(state);

onMounted(() => {
  // colorList
  // const list = Object.keys(colorName).map(item => {
  //   return {
  //     label: item,
  //     value: item
  //   };
  // });
  // console.log(list);
  // colorList.value
});
</script>

<template>
  <el-card shadow="never">
    <template #header>
      <h2>{{ route.query.name }}</h2>
    </template>
    <PlusPage
      ref="plusPageInstance"
      :pagination="{
        background: true
      }"
      :is-card="false"
      :request="getList"
      :columns="columns"
      :params="state.query"
      :search="{ labelWidth: '100px', colProps: { span: 8 } }"
      :table="{
        isSelection: true,
        actionBar: { buttons, width: 140 },
        onClickAction: handleTableOption,
        onSelectionChange: handleSelect
      }"
    >
      <template #search-footer>
        <h2 class="hidden">defult</h2>
      </template>
      <template #table-title>
        <el-row class="button-row">
          <el-button type="primary" :icon="Plus" @click="handleCreate">
            添加
          </el-button>
          <el-button :icon="Delete" type="danger" @click="handleBatchDelete">
            批量删除
          </el-button>
        </el-row>
      </template>
    </PlusPage>

    <!-- 弹窗编辑 -->
    <PlusDrawerForm
      v-model:visible="visible"
      v-model="form"
      :form="{ columns, labelPosition: 'top', rules }"
      :title="dialogTitle"
      @confirm="handleSubmit"
      @cancel="handleCancel"
    />

    <!-- 查看弹窗 -->
    <PlusDialog
      v-model="detailsVisible"
      width="600px"
      title="用户组详情"
      top="26vh"
      :has-footer="false"
    >
      <PlusDescriptions :column="2" :columns="columns" :data="currentRow" />
    </PlusDialog>
  </el-card>
</template>
